/**
 * Copyright (C), 2015-2019, XXX有限公司
 * FileName: CommodityServiceImpl
 * Author:   pc
 * Date:     2019/9/2 16:30
 * Description: 实现服务类
 * History:
 * <author>          <time>          <version>          <desc>
 * 作者姓名           修改时间           版本号              描述
 */
package com.example.rabbitmqdemo.service.impl;

import com.alibaba.fastjson.JSON;
import com.example.rabbitmqdemo.entity.Commodity;
import com.example.rabbitmqdemo.Repository.CommodityRepository;
import com.example.rabbitmqdemo.service.CommodityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * 〈功能：〉<br> 
 * 〈实现服务类〉
 * @author liuhaoran
 * @create 2019/9/2 16:30
 * @since 1.0.0
 */
@Service
public class CommodityServiceImpl implements CommodityService {
	@Autowired
	CommodityRepository commoditymapper;
	@Autowired
	private RedisTemplate redisTemplate;
	@Override
	public List<Commodity> getCommodityList() {
		String key = "commoditylist";
		List<Commodity> listcommodity = new ArrayList<>();
		ValueOperations<String,String> operations = redisTemplate.opsForValue();
		ListOperations<String, Object> lo = redisTemplate.opsForList();
		listcommodity = commoditymapper.getCommodityList();
		boolean hasKey = redisTemplate.hasKey(key);
		if(hasKey){
			//listcommodity = operations.get(key);
			//listcommodity = lo.getOperations(key);
			System.out.println("缓存中获取的数据获取的信息");
			return listcommodity;
		} else {

			System.out.println("访问数据库获取的信息");
			//operations.set(key, gson.fromJson(listcommodity),5, TimeUnit.HOURS);
			lo.rightPush(key, listcommodity,5);
			return listcommodity;
		}
	}

	@Override
	public Map<String,Object> selectComodityById(int id) {
		ValueOperations<String, Map<String, Object>> operations = redisTemplate.opsForValue();
		Map<String,Object> map = new HashMap<String,Object>();
		ListOperations<String, Object> lo = redisTemplate.opsForList();
		Commodity commoditylist;
		boolean hasKey = redisTemplate.hasKey("commodity"+id);
		if(hasKey) {
			Object StrMapObj=operations.get("commodity"+id);
			map.put("commodity"+id,StrMapObj);
			String json= JSON.toJSONString(StrMapObj);
			System.out.println("缓存数据=======");
			System.out.println(map);
		} else {
			commoditylist=commoditymapper.selectCommodityById(id);
			map.put("commodity"+commoditylist.getId(),commoditylist);
			//redisTemplate.opsForValue().multiSet(map);
			operations.set("commodity"+commoditylist.getId(),map ,60, TimeUnit.SECONDS);
			System.out.println("数据库读取并加入缓存");
			System.out.println(commoditylist);
		}
		return map;
	}
}